package w_mapper

import (
	"context"
	"gorm.io/gorm"
	"wms-go/web/w_model"
)

type KcMapper struct {
	DB  *gorm.DB
	Ctx context.Context
}

func (mapper *KcMapper) Create(m *w_model.SKc) (ret *w_model.SKc, err error) {
	if err := mapper.DB.WithContext(mapper.Ctx).Create(m).Error; err != nil {
		return nil, err
	}
	return m, nil
}
func (mapper *KcMapper) Update(m *w_model.SKc) (ret *w_model.SKc, err error) {
	if err := mapper.DB.WithContext(mapper.Ctx).Model(&w_model.SKc{}).Where("id = ?", m.ID).Updates(m).Error; err != nil {
		return nil, err
	}
	return m, nil
}
func (mapper *KcMapper) CreateOrUpdate(m *w_model.SKc) (ret *w_model.SKc, err error) {
	if err := mapper.DB.WithContext(mapper.Ctx).Model(m).Save(m).Error; err != nil {
		return nil, err
	}
	return m, nil
}
func (mapper *KcMapper) QueryById(id string) (m *w_model.SKc, err error) {
	if err := mapper.DB.WithContext(mapper.Ctx).Model(&w_model.SKc{}).Where("id = ?", id).First(&m).Error; err != nil {
		return nil, err
	}
	return m, nil
}
func (mapper *KcMapper) QueryByIds(ids []string) (m []*w_model.SKc, err error) {
	if err := mapper.DB.WithContext(mapper.Ctx).Model(&w_model.SKc{}).Where("id IN ?", ids).Find(&m).Error; err != nil {
		return nil, err
	}
	return m, nil
}
func (mapper *KcMapper) DeleteById(id string) (err error) {
	if err := mapper.DB.WithContext(mapper.Ctx).Unscoped().Where("id = ?", id).Delete(&w_model.SKc{}).Error; err != nil {
		return err
	}
	return nil
}

func (mapper *KcMapper) DeleteByIds(ids []string) (err error) {
	if err := mapper.DB.WithContext(mapper.Ctx).Unscoped().Where("id IN ?", ids).Delete(&w_model.SKc{}).Error; err != nil {
		return err
	}
	return nil
}

func (mapper *KcMapper) Page(pageIndex, pageSize int) (items []*w_model.SKc, count int64, err error) {
	var countTmp int64 = 0
	table := mapper.DB.WithContext(mapper.Ctx)
	if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&items).Offset(-1).Limit(-1).Count(&countTmp).Error; err != nil {
		return nil, 0, err
	}
	return items, countTmp, nil
}

func (mapper *KcMapper) List() (items []*w_model.SKc, count int64, err error) {
	var countTmp int64 = 0
	table := mapper.DB.WithContext(mapper.Ctx)
	if err := table.Find(&items).Offset(-1).Limit(-1).Count(&countTmp).Error; err != nil {
		return nil, 0, err
	}
	return items, countTmp, nil
}
